package com.example.day09_zuoye;

import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.example.day09_zuoye.adap.Fragment_Adapter;
import com.example.day09_zuoye.frag.ShouYe_Fragment;
import com.example.day09_zuoye.frag.XiaZai_Fragment;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private Toolbar mToo;
    private ViewPager mVp;
    private TabLayout mTab;
    private ArrayList<Fragment> list;
    private ShouYe_Fragment shouYe_fragment;
    private XiaZai_Fragment xiaZai_fragment;
    private Fragment_Adapter fragment_adapter;
    private TextView too_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initToo();
        initVp();
    }

    private void initVp() {
        list = new ArrayList<>();
        shouYe_fragment = new ShouYe_Fragment();
        xiaZai_fragment = new XiaZai_Fragment();
        list.add(shouYe_fragment);
        list.add(xiaZai_fragment);
        fragment_adapter = new Fragment_Adapter(getSupportFragmentManager(), list);
        mVp.setAdapter(fragment_adapter);
        mTab.setupWithViewPager(mVp);

        mTab.getTabAt(0).setText("首页");
        mTab.getTabAt(1).setText("下载");
    }

    private void initToo() {
        mTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                too_text.setText(tab.getText());
                FragmentManager manager = getSupportFragmentManager();
                if (tab.getPosition() == 0) {
                    manager.beginTransaction().
                            show(shouYe_fragment).
                            hide(xiaZai_fragment).
                            commit();
                } else {
                    manager.beginTransaction().
                            show(xiaZai_fragment).
                            hide(shouYe_fragment).
                            commit();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initView() {
        mToo = (Toolbar) findViewById(R.id.Too);
        mVp = (ViewPager) findViewById(R.id.Vp);
        mTab = (TabLayout) findViewById(R.id.Tab);
        too_text = (TextView) findViewById(R.id.too_text);
        mToo.setTitle("");
        setSupportActionBar(mToo);
    }
}
